<template>
  <div>
    <div class="app-container calendar-list-container">
      <el-row>
        <el-col :span="24">
          <div>
            <TableFrom :list="table.list"
                       @handleSelectionChange="handleSelectionChange"
                       :options="options"
                       :columns="table.columns"
                       :operates="operates"
                       :formItems="formItems"
                       :tabFrom="tabFrom"
                       :pagination="pagination"
                       ref="productInfo"
                       @submit="handleSubmit"
                       @batchSubmit="batchDataClick"
                       @handleSizeChange="handleSizeChange"
                       @handleCurrentChange="handleCurrentChange"
                       @newAdd="newAdd">
            </TableFrom>
          </div>
        </el-col>
      </el-row>
    </div>
    <div id="product">
      <CustomColumn :show.sync="showCustomColumn"
                    localName="productInfo"
                    :baseColumns="columns"
                    :defaultColumns="defaultColumns"
                    :columns.sync="table.columns" />
    </div>
    <div class="drawer">
      <el-drawer :title="title"
                 :before-close="handleClose"
                 :visible.sync="showDrawer"
                 :show-close="false"
                 direction="rtl"
                 custom-class="demo-drawer"
                 size="60%"
                 ref="drawer"
                 @close="resetForm">
        <div class="demo-drawer__content">
          <el-row :gutter="20">
            <el-form ref="formData"
                     :model="formData"
                     :rules="rules"
                     size="medium"
                     label-width="100px">
              <el-col :span="24">
                <el-form-item label="商品名称："
                              prop="productName">
                  <el-input v-model="formData.productName"
                            placeholder="请输入商品名称："
                            clearable
                            :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品分类："
                              prop="categoryId">
                  <el-select v-model="formData.categoryId"
                             placeholder="请选择商品分类："
                             clearable
                             :style="{width: '100%'}">
                    <el-option v-for="(item, index) in categoryIdOptions"
                               :key="index"
                               :label="item.label"
                               :value="item.value"
                               :disabled="item.disabled"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="单位："
                              prop="unit">
                  <el-select v-model="formData.unit"
                             placeholder="请选择单位："
                             clearable
                             :style="{width: '100%'}">
                    <el-option v-for="(item, index) in unitOptions"
                               :key="index"
                               :label="item.label"
                               :value="item.value"
                               :disabled="item.disabled"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品售价："
                              prop="salePrice">
                  <el-input-number v-model="formData.salePrice"
                                   placeholder="商品售价："
                                   :step='1'
                                   :precision='2'>
                  </el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品进价："
                              prop="purchasePrice">
                  <el-input-number v-model="formData.purchasePrice"
                                   placeholder="商品进价："
                                   :step='1'
                                   :precision='2'>
                  </el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="售卖状态："
                              prop="status"
                              required>
                  <el-switch v-model="formData.status"
                             :active-value='0'
                             :inactive-value='2'></el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品库存："
                              prop="stockQuantity">
                  <el-input-number v-model="formData.stockQuantity"
                                   placeholder="商品库存："
                                   :step='1'></el-input-number>
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </div>
        <div class="details-drawer-bottom">
          <div class="details-drawer-bottom-button">
            <el-button class="custom-button green-button"
                       icon="el-icon-circle-close">取消</el-button>
            <el-button type="primary"
                       class="custom-button red-button"
                       icon="el-icon-circle-check"
                       @click="add">保存并提交</el-button>
          </div>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import TableFrom from '@/components/packages/publicTable.vue';
export default {
  name: 'productInfo',
  components: {
    TableFrom,
  },
  data() {
    return {
      title: '',
      showCustomColumn: false,
      showDrawer: false,
      batchDelete: [], //删除用户的id
      table: {
        list: [],
        columns: [],
      },
      rules: {
        productName: [
          {
            required: true,
            message: '请输入商品名称：',
            trigger: 'blur',
            show: true,
          },
        ],
        categoryId: [
          {
            required: true,
            message: '请选择商品分类：',
            trigger: 'change',
          },
        ],
        unit: [
          {
            required: true,
            message: '请选择单位：',
            trigger: 'change',
            show: true,
          },
        ],
        salePrice: [
          {
            required: true,
            message: '商品售价：',
            trigger: 'blur',
          },
        ],
        purchasePrice: [
          {
            required: true,
            message: '商品进价：',
            trigger: 'blur',
          },
        ],
        stockQuantity: [
          {
            required: true,
            message: '商品库存：',
            trigger: 'blur',
          },
        ],
      },
      formItems: [
        {
          lable: '商品分类：',
          type: 'dropDown',
          key: 'categoryId',
          placeholder: '请选择商品分类',
          option: this.categoryIdOptions,
          style: { width: '200px' },
        },
        {
          lable: '商品名称：',
          type: 'input',
          key: 'productName',
          placeholder: '请输入商品名称',
          style: { width: '200px' },
        },
      ],

      list: [], // table数据
      listParm: {
        page: 1,
        size: 10,
        start: '',
        end: '',
        productName: '',
        categoryId: '',
      },
      options: {
        stripe: true, // 是否为斑马纹 table
        highlightCurrentRow: true, // 是否支持当前行高亮显示
        indexList: true,
        page: true,
        mutiSelect: true, // 是否支持列表项选中功能
      }, // table 的参数
      //表头操作
      tabFrom: {
        selectButton: true, //是否展示查询按钮
        newAdd: true,
        batch: true, //是否展示批量删除按钮
        batchDisabled: true, //批量删除按钮是否置灰
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        totalCount: 0,
      },
      defaultColumns: [],
      columns: [
        {
          key: 'productName',
          label: '商品名称',
          align: 'center',
          prop: 'productName',
        },
        {
          key: 'categoryId',
          label: '商品分类',
          align: 'center',
          prop: 'categoryId',
          formatter: (row, col, cellValue) => {
            return this.getCategoryLabel(row.categoryId);
          },
        },
        {
          key: 'unit',
          label: '单位',
          align: 'center',
          prop: 'unit',
        },
        {
          key: 'salePrice',
          label: '售价',
          align: 'center',
          prop: 'salePrice',
          formatter: (row, col, cellValue) => {
            return row.salePrice + '元';
          },
        },
        {
          key: 'purchasePrice',
          label: '进价',
          align: 'center',
          prop: 'purchasePrice',
          formatter: (row, col, cellValue) => {
            return row.purchasePrice + '元';
          },
        },
        {
          key: 'stockQuantity',
          label: '商品库存',
          align: 'center',
          prop: 'stockQuantity',
        },
        {
          key: 'createTime',
          label: '创建时间',
          align: 'center',
          prop: 'createTime',
        },
      ], // 需要展示的列
      formData: {
        productName: undefined,
        categoryId: undefined,
        unit: undefined,
        salePrice: 0,
        purchasePrice: 0,
        status: 0,
        stockQuantity: 0,
      },
      categoryIdOptions: [],
      unitOptions: [
        {
          label: '包',
          value: '包',
        },
        {
          label: '袋',
          value: '袋',
        },
        {
          label: '杯',
          value: '杯',
        },
        {
          label: '盒',
          value: '盒',
        },
        {
          label: '壶',
          value: '壶',
        },
        {
          label: '个',
          value: '个',
        },
        {
          label: '副',
          value: '副',
        },
        {
          label: '听',
          value: '听',
        },
        {
          label: '桶',
          value: '桶',
        },
        {
          label: '瓶',
          value: '瓶',
        },
      ],
      operates: {
        width: 150,
        list: [
          {
            id: '1',
            label: '编辑',
            style: 'cursor:pointer;color: #409eff;',
            show: true,
            class: 'el-icon-edit',
            plain: true,
            method: (scope, row) => {
              this.handleEdit(row.id);
            },
          },
          {
            id: '2',
            label: '删除',
            style: 'cursor:pointer;color: #b3450e;',
            class: 'el-icon-delete',
            show: true,
            plain: false,
            method: (index, row) => {
              this.handleDel(row.id);
            },
          },
        ],
      }, // 列操作按钮
    };
  },
  created() {
    this.getSelect();
  },
  mounted: function () {
    var _this = this;
    this.getList(1, this.pagination.pageSize);
    window.bus.$on('blogTableReload', function () {
      _this.getList(_this.pagination.currentPage, _this.pagination.pageSize);
    });
  },
  methods: {
    // 选中行
    handleSelectionChange(val) {
      this.batchDelete = val;
      if (this.batchDelete.length > 0) {
        this.tabFrom.batchDisabled = false;
      } else {
        this.tabFrom.batchDisabled = true;
      }
    },
    //单条删除
    async handleDel(index) {
      var _this = this;
      const confirmResult = await this.$messageIndex.MessageBoxQuestion(
        '删除后将无法逆转，是否继续？'
      );
      if (confirmResult) {
        _this.batchDelete.push(index);
        _this.deleteRow();
      }
    },
    //批量删除按钮点击
    async batchDataClick(val) {
      if (val) {
        var _this = this;
        const confirmResult = await this.$messageIndex.MessageBoxQuestion(
          '删除后将无法逆转，是否继续？'
        );
        if (confirmResult) {
          let deleteData = this.batchDelete.map((item) => {
            const id = item.id;
            return id;
          });
          this.batchDelete = deleteData;
          _this.deleteRow();
        }
      }
    },
    //删除执行
    async deleteRow() {
      var _this = this;
      let requestData = {
        ids: _this.batchDelete,
      };
      let res = await this.$api.productInfoApi.delete(requestData, {
        loadingTime: 100,
        loadingText: '数据执行中...',
      });
      if (!res.data) {
        this.$messageIndex.Notice('成功', '商品信息删除成功', 'success');
      } else {
        this.$messageIndex.Notice('错误', res.msg + '--删除失败', 'error', '0');
      }
      this.batchDelete = [];
      this.getList(_this.pagination.currentPage, _this.pagination.pageSize);
    },
    getButtonInfo(status) {
      let buttonName = '';
      let buttonType = '';

      switch (status) {
        case 0:
          buttonName = '正常';
          buttonType = 'success';
          break;
        case 1:
          buttonName = '异常';
          buttonType = 'danger';
          break;
        // 其他状态的处理逻辑
        default:
          break;
      }

      return { buttonName, buttonType };
    },
    customArr(val) {
      this.showCustomColumn = true;
    },
    search() {
      this.getList(1, this.pagination.pageSize);
    },
    handleSubmit(formDataInfo) {
      var _this = this;
      _this.listParm = formDataInfo;
      _this.getList(1, this.pagination.pageSize);
    },

    async getList(page, size) {
      var _this = this;
      if (page) _this.listParm.page = page;
      if (size) _this.listParm.size = size;
      let res = await this.$api.productInfoApi.list(_this.listParm, {
        loadingTime: 100,
        loadingText: '数据加载中...',
      });
      if (res) {
        this.table.list = res.records;
        this.pagination.currentPage = res.current;
        this.pagination.totalCount = res.total;
      }
    },
    /**
     * 新增按钮触发
     */
    async newAdd(val) {
      this.title = '新增商品';
      // this.getSelectValue();
      if (val) {
        this.showDrawer = true;
      }
    },
    async add() {
      let res;
      var _this = this;
      if (await this.validateData()) {
        if (this.title == '新增商品') {
          res = await this.$api.productInfoApi.add(_this.formData, {
            loadingTime: 100,
            loadingText: '数据执行中...',
          });
        } else {
          res = await this.$api.productInfoApi.update(_this.formData, {
            loadingTime: 100,
            loadingText: '数据执行中...',
          });
        }
        if (res.code == 200) {
          await this.$messageIndex.Notice(
            '成功',
            this.title + '成功',
            'success'
          );
          this.showDrawer = false;
          this.getList(1, this.pagination.pageSize);
        } else {
          this.$messageIndex.Notice(
            '错误',
            this.title + '失败：' + res.msg + '',
            'error',
            '0'
          );
          return false;
        }
      }
    },
    /**
     * 校验数据
     */
    async validateData() {
      return new Promise((resolve, reject) => {
        this.$refs.formData.validate((valid) => {
          if (valid) {
            resolve(true);
          } else {
            resolve(false);
          }
        });
      });
    },
    /**
     * 获取商品分类下拉框
     */
    async getSelect() {
      let res = await this.$api.productCategoryApi.getSelect(
        {},
        {
          loadingTime: 100,
          loadingText: '数据加载中...',
        }
      );
      if (res) {
        this.categoryIdOptions = res;
        this.updateFormItemsOptions();
      }
    },
    updateFormItemsOptions() {
      // 查找要更新的表单项并更新其 option 属性
      const formItem = this.formItems.find((item) => item.key === 'categoryId');
      if (formItem) {
        formItem.option = this.categoryIdOptions;
      }
    },
    /**
     * 根据分类id匹配中文
     * @param categoryId 商品分类id
     */
    getCategoryLabel(categoryId) {
      const option = this.categoryIdOptions.find(
        (option) => option.value === categoryId
      );
      return option ? option.label : '未知分类';
    },
    /**
     * 编辑按钮出发
     **/
    async handleEdit(val) {
      this.title = '编辑商品';
      // this.getSelectValue();
      if (val) {
        this.showDrawer = true;
      }
      let res = await this.$api.productInfoApi.byId(
        { id: val },
        {
          loadingTime: 100,
          loadingText: '数据加载中...',
        }
      );
      if (res) {
        this.formData = res;
      }
      this.$forceUpdate();
    },
    handleSizeChange(val) {
      this.listParm.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listParm.page = val;
      this.getList();
    },
    resetForm() {
      this.$refs.formData.resetFields();
    },
  },
};
</script>
<style scoped lang="less">
.drawer /deep/ .el-drawer__header {
  background-color: rgb(255, 255, 255);
  flex: none;
  padding: 0px 20px;
  height: 50px;
  color: #000000;
  margin-bottom: 0px;
  box-shadow: rgba(0, 0, 0, 0.35) 0px 1px 5px;
}
.drawer /deep/ .el-drawer__title {
  font-size: 20px;
}
.form /deep/ .el-form-item__label {
  color: black;
}
.form /deep/ .el-input__inner {
  width: 70%;
}
.drawer /deep/ .demo-drawer__content {
  margin-top: 20px;
  padding: 0px 20px;
}
.details-drawer-bottom {
  position: absolute;
  bottom: 0;
  width: 100%;
  display: flex;
  align-items: center;
  /* 垂直居中 */
  justify-content: flex-end;
  /* 将子元素靠右对齐 */
  background-color: white;
  z-index: 1000;
  padding: 10px 20px;
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
}
</style>
<style>
.drawer-button {
  position: absolute;
  right: 10%;
}
</style>
